
var CONTACTS_FEED = 'https://www.google.com/m8/feeds/contacts/default/full';
var GROUPS_FEED = 'https://www.google.com/m8/feeds/groups/default/full';

var background = chrome.extension.getBackgroundPage();
var sandboxGroupId = null;
var contacts = new Array();


function Login() {
	background.Authorize( LoggedIn );
}

function CreateLoginButton() {
	$('<button>', {
		type: "button",
		text: "Login",
		onclick: Login
	}).appendTo('body');
}

function LoggedIn() {
	console.log( 'LoggedIn()' );
	$('#logged_in').show();
	
	GetGroupId( 'Sandbox', function( id ) {
		sandboxGroupId = id;
		GetAllContacts();
	});
}

function ProcessSinglePhoneNumber( name, number ) {
	$('#contact_table > tbody:last').append(
		'<tr><td>' + name + '</td><td>' + number + '</td></tr>' );
		
	contacts.push( new Contact( name, number ) );
}

function ProcessSingleContact( entry ) {
	for( var i = 0, number; number = entry.gd$phoneNumber[i]; ++i ) {
		ProcessSinglePhoneNumber( entry.title.$t, number.$t );
	}
}

function ContactsReceived( response, xhr ) {
	console.log( 'Contacts Received' );
	var data = JSON.parse( response );
	console.log( data );
	for( var i = 0, entry; entry = data.feed.entry[i]; ++i ) {
		ProcessSingleContact( entry );
	}
}

function GetAllContacts() {
	var params = {
		'alt': 'json',
		'max-results': 50,
		'group': sandboxGroupId // @todo Remove group parameter for release
	}
	
	background.SendSignedRequest( CONTACTS_FEED, ContactsReceived, params );
}

function FindGroupByName( name, groups ) {
	for( var i = 0, group; group = groups[i]; ++i ) {
		if( group.title.$t == name ) {
			return group.id.$t;
		}
	}
}

function GetGroupId( groupName, callback ) {
	var onReceiveGroups = function( request, xhr ) {
		console.log( 'All Groups Received' );
		var data = JSON.parse( request );
		var groupId = FindGroupByName( groupName, data.feed.entry );
		callback( groupId );
	}
	
	var params = {
		'alt': 'json',
		'max-results': 50000
	}

	background.SendSignedRequest( GROUPS_FEED, onReceiveGroups,  params );
}

function GetSelectedPhoneFormat() {
	var selection = $('input[name=phone-format-radio]:checked').val();
	if( !selection ) {
		throw 'Please make a format selection';
	}
	
	var index = parseInt( selection );
	return phoneFormats[index];
}

function FormatNumbers( format, processor ) {
	for( var i = 0, contact; contact = contacts[i]; ++i ) {
		var name = contact.name;
		var number = contact.FormatNumber( format, true );
		processor( name, number );
	}
}

function ClearPreviewTable() {
	$('#preview_table').find( 'tr:gt(0)' ).remove();
}

function OnPreview( event ) {
	try {
		ClearPreviewTable();
		var format = GetSelectedPhoneFormat();
		FormatNumbers( format, function( name, number ) {
			$('#preview_table > tbody:last').append(
				'<tr><td>' + name + '</td><td>' + number + '</td></tr>' );
		});
	}
	catch( err ) {
		alert( err );
	}
}

function OnConvert( event ) {
}

function InitializeEventHandlers() {
	$('#btnConvert').click( OnConvert );
	$('#btnPreview').click( OnPreview );
}

function Initialize() {
	InitializeEventHandlers();
	CreatePhoneFormatRadioButtons( '#phone-formats' );
	
	if( background.IsLoggedIn() ) {
		LoggedIn();
	}
	else {
		CreateLoginButton();
	}
}

$(Initialize);